#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    status = false;
    connect(&tcpSocket, SIGNAL(connect()), this, SLOT(onConnected()));
    connect(&tcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    connect(&tcpSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError()));
}

Dialog::~Dialog()
{
    delete ui;
}


void Dialog::on_sendButton_clicked()
{
    QString msg = ui->messageEdit->text();
    if(msg == ""){
        return;
    }
    msg = username + "：" + msg;
    tcpSocket.write(msg.toUtf8());
    ui->messageEdit->clear();
}

void Dialog::on_connectButton_clicked()
{
    if(status == false){
        serverIP.setAddress(ui->serverIpEdit->text());
        serverPort = ui->serverPortEdit->text().toShort();
        tcpSocket.connectToHost(serverIP, serverPort);
    }else{
        QString msg = username + "：离开了聊天室";
        tcpSocket.write(msg.toUtf8());
        tcpSocket.disconnectFromHost();
    }
}

void Dialog::onConnected(){
    status = true;
    ui->sendButton->setEnabled(true);
    ui->serverIpEdit->setEnabled(false);
    ui->serverPortEdit->setEnabled(false);
    ui->userNameEdit->setEnabled(false);
    ui->connectButton->setText("离开聊天室");
}
void Dialog::onDisconnected(){
    status = false;
    ui->sendButton->setEnabled(true);
    ui->serverIpEdit->setEnabled(false);
    ui->serverPortEdit->setEnabled(false);
    ui->userNameEdit->setEnabled(false);
    ui->connectButton->setText("连接服务器");
}
void Dialog::onReadyRead(){
    if(tcpSocket.bytesAvailable()){
        QByteArray a = tcpSocket.readAll();
        ui->listWidget->addItem(a);
        ui->listWidget->scrollToBottom();
    }
}
void Dialog::onError(){
    QMessageBox::critical(this, "Error", tcpSocket.errorString());
}
